from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session
from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.response_code import RET
from info.modules.index import index_blu
from flask import g
from info.utils.common import user_login_data

@index_blu.route('/news_list')
def news_list():
    """
        获取首页新闻数据

    """
    # 1. 获取参数
    # 新闻的分类id
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")
    # 2. 校验参数
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数")

    # 在首页中等待审核的新闻不显示
    filters = [News.status == 0]
    if cid != 1:  # 查询的不是最新的数据
        # 只有点击其他分类才会分类新闻,最新分类的新闻不分类
        filters.append(News.category_id == cid)
    # 3. 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    # 取到当前页的数据
    news_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page
    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
            "total_page": total_page,
            "current_page": current_page,
            "news_dict_li": news_dict_li
                             }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

# 首页显示路由
@index_blu.route("/")
@user_login_data
def index():
    """"
    显示首页
    1,如果用户已经登陆,将当前登陆用户的数据传递到模板中,供模板显示
    """
    # 获取用户的id
    # user_id = session.get("user_id", None)  # 取不到返回none
    # user = None
    # if user_id:
    #     # 尝试查询用户的模型
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user

    # 右侧新闻排行的逻辑
    new_list = []
    try:
        new_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 定义一个空字典列表,遍历新闻列表对象,取出每一项取出对应的值
    news_dict_li = []
    for news in new_list:
        news_dict_li.append(news.to_basic_dict())

    # 查询分类数据,通过模板的形式渲染出来
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_li = []
    for category in categories:
        category_li.append(category.to_dict())


    data = {
        # 如果user不为none显示user.to_dict(), 否则返回none
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "category_li": category_li
    }
    # 将取到的数据返回到模板中
    return render_template("news/index.html", data=data)



# 在打开网页时浏览器会默认去请求跟路径favicon.ico做网站标签的小图标
# send_static_file是flask去查找指定静态文件所调用的方法
@index_blu.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")